package com.dxy.hms.manager;

import cn.hutool.core.collection.CollUtil;
import com.dxy.hms.cache.ExpiringCache;
import com.dxy.hms.cache.ICache;
import com.dxy.hms.model.entity.Dict;
import com.dxy.hms.mapper.DictMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class DictCacheManager {

    public static DictCacheManager INSTANCE;

    @Autowired
    private DictMapper dictMapper;

    @Value("${cache.conf.dictCacheDuration:1}")
    private Integer dictCacheDuration;

    private ICache<String, List<Dict>> dictCache;

    @PostConstruct
    public void init(){
        dictCache = new ExpiringCache<String, List<Dict>>()
                .setDuration(dictCacheDuration)
                .setTimeUnit(TimeUnit.HOURS)
                .setLoader(this::loadDictOptions);
        DictCacheManager.INSTANCE = this;
    }

    private List<Dict> loadDictOptions(String dictKey){
        log.info("======>加载字典选项, dictKey: {}", dictKey);
        // TODO目前仅支持使用parent_id这一种方式
        List<Dict> dictList = dictMapper.getByDictCode(dictKey);
        // 要以null来判断字典存不存在
        return CollUtil.isNotEmpty(dictList) ? dictList : null;
    }

    public List<Dict> getDictOptions(String dictKey){
        return dictCache.get(dictKey);
    }

    public String getDictName(String dictKey, String optionCode){
        List<Dict> list = getDictOptions(dictKey);
        if (CollUtil.isNotEmpty(list)){
            for (Dict dict : list) {
                if (dict.getDictCode().equals(optionCode)){
                    return dict.getDictName();
                }
            }
        }
        return "";
    }

    public void remove(String dictKey){
        dictCache.remove(dictKey);
    }

    public void removeAll(){
        dictCache.removeAll();
    }
}
